package pers.wang.toolset.ali.rocketmq.spring.boot.autoconfigure;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.transaction.LocalTransactionChecker;
import com.aliyun.openservices.ons.api.transaction.TransactionStatus;
public class TransactionChecker implements LocalTransactionChecker,ApplicationContextAware {
	private static final Logger LOG = LoggerFactory.getLogger(TransactionChecker.class);
	private TransactionCheckerCallback callback;
	@Override
	public TransactionStatus check(Message msg) {
		TransactionStatus result = TransactionStatus.Unknow;
		if(callback != null) {
			try {
				boolean checkResult = callback.check(msg);
				result = checkResult ? TransactionStatus.CommitTransaction : TransactionStatus.RollbackTransaction;
			} catch (Exception e) {
				LOG.error("事务消息回查失败，错误信息:{}",e);
			}
		}
		return result;
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String, TransactionCheckerCallback> callbackMap = applicationContext.getBeansOfType(TransactionCheckerCallback.class);
		if(callbackMap.size() == 0) {
			LOG.warn("未发现事务消息回查回调");
		}
		if(callbackMap.size() > 1) {
			LOG.error("发现多个事务消息回查callback");
			throw new Error("发现多个事务消息回差callback:" + callbackMap) ;
		}
		callbackMap.forEach((name,bean) ->{
			this.callback = bean;
			LOG.info("事务消息callback检查:beanName:{},beanClass:{}",name,bean.getClass());
		});
		
	}
}
